import os
import sys
import re
from kconfiglib import Kconfig
from menuconfig import menuconfig

def mconf_set_env(path):
    """
    Set Kconfig Env
    """
    os.environ["MENUCONFIG_STYLE"] = (
        "aquatic "
        "path=fg:cyan,bg:#01549e "
        "separator=fg:cyan,bg:white "
        "list=fg:black,bg:#cacaca "
        "selection=fg:white,bg:#01549e "
        "help=fg:black,bg:#cacaca "
        )
    os.environ["KCONFIG_CONFIG"] = os.path.join(".config")
    os.environ["KCONFIG_CONFIG_HEADER"] = "# Generated by Kconfig\n"
    os.environ["CONFIG_"] = ""

def mk_config(filename):
    try:
        config = open(filename, 'r')
    except:
        print('open config:%s failed' % filename)
        return

    rtconfig = open('config.h', 'w')
    rtconfig.write('#ifndef __CONFIG_H__\n')
    rtconfig.write('#define __CONFIG_H__\n\n')

    empty_line = 1

    for line in config:
        line = line.lstrip(' ').replace('\n', '').replace('\r', '')

        if len(line) == 0:
            continue

        if line[0] == '#':
            if len(line) == 1:
                if empty_line:
                    continue

                rtconfig.write('\n')
                empty_line = 1
                continue

            if 'is not set' in line:
                continue
            else:
                line = line[1:]
                rtconfig.write('/*%s */\n' % line)

            empty_line = 0
        else:
            empty_line = 0
            setting = line.split('=')
            if len(setting) >= 2:
                if setting[1] == 'y':
                    rtconfig.write('#define %s\n' % setting[0])
                else:
                    rtconfig.write('#define %s %s\n' % (setting[0], re.findall(r"^.*?=(.*)$",line)[0]))

    rtconfig.write('\n')
    rtconfig.write('#endif\n')
    rtconfig.close()

if __name__ == "__main__":
    path = os.getcwd()
    mconf_set_env(path)
    kconf = Kconfig(filename='./Kconfig')
    menuconfig(kconf)
    mk_config('.config')

